package com.mongodb.service;

import com.alibaba.fastjson.JSON;
import com.mongodb.document.User;
import com.mongodb.mapper.UserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

/**
 * @author zhangbowen
 * @date 2019/2/15
 **/
@Service
public class TransactionService {
    @Autowired
    private MongoTemplate mongoTemplate;
    @Autowired
    private UserMapper userMapper;

    @Transactional //(value = "mysqlTransactionManager")
    public void addUser() {
        userMapper.addUser("张三", 18);
        userMapper.addUser("李四", 17);
        int i = 1 / 0;
    }

    @Transactional //(value = "mongodbTransactionManager")
    public void addUser1() {
        User user = new User();
        user.setName("张三");
        user.setAge(17);
        mongoTemplate.save(user);
        User user1 = new User();
        user1.setName("张三1");
        user1.setAge(171);
        mongoTemplate.save(user1);
        int i = 1 / 0;
    }

    public static void main(String[] args) {
        int[] array = new int[]{6,5,1,6,8,3,5,79,103,6,1,8,3,2,4};
        sort(array, 0, array.length - 1);
    }

    public static int partition(int[] array, int lo, int hi) {
        int mid = lo + (hi - lo) / 2;
        if (array[hi] < array[mid]) {
            int temp = array[mid];
            array[mid] = array[hi];
            array[hi] = temp;
        }
        if (array[hi] < array[lo]) {
            int temp = array[hi];
            array[hi] = array[lo];
            array[lo] = temp;
        }
        if (array[lo] < array[mid]) {
            int temp = array[lo];
            array[lo] = array[mid];
            array[mid] = temp;
        }
        int temp = array[lo];
        while (lo < hi) {
            while (array[hi] >= temp && lo < hi) {
                hi--;
            }
            array[lo] = array[hi];
            while (array[lo] <= temp && lo < hi) {
                lo++;
            }
            array[hi] = array[lo];
        }
        array[lo] = temp;
        return lo;
    }

    public static void sort(int[] array, int lo, int hi) {
        if (lo >= hi) {
            return;
        }
        int index = partition(array, lo, hi);
        sort(array, index + 1, hi);
        sort(array, lo, index - 1);
        System.out.println(JSON.toJSONString(array));
    }
}
